package com.atguigu.educenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstantWxUtils;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller //不给前端返回数据 仅仅对页面进行重定向
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxCodeController {

    @Autowired
    private UcenterMemberService ucenterMemberService;
    //获取扫描人信息 添加数据
    @GetMapping("callback")//参数为扫描二维码后重定向后的地址中所带的参数  在这个方法中进行接收
    public  String callback(String code,String state){
       /* 获取路径上参数的值 key必须和路径参数上的key相同
        System.out.println("code::"+code);
        System.out.println("state::"+state);
        code::071x6YFa1QO7CA0NHzFa1HcQTu3x6YFQ
        state::guli*/

        try {
            //获取路径上参数code的值 临时票据
            //向认证服务器发送请求换取access_token  固定路径
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            //使用String方法进行传值
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            //请求这个拼接好的地址 得到两个返回值 access_token和openId
            //使用httpclien发送请求  得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //从accessTokenInfo中获取两个返回值  access_token和openId
            //accessTokenInfo为json字符串 使用json转换工具将其转成map
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");


            //得到扫码人信息后 将扫码人信息存放到数据库中
            //存之前先查看扫码人是否已经注册
            UcenterMember member =  ucenterMemberService.getMember(openid);
            if(member==null){
                //3拿着得到的 access_token和openId 再去请求微信提供的固定地址
                //访问微信的资源服务器  获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //得到需要访问的url
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                //通过httpclent发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //将userInfo字符串转化成map类型
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);

                String nickname = (String) userInfoMap.get("nickname"); //获取扫码人的昵称
                String headimgurl = (String) userInfoMap.get("headimgurl");//获取扫码人的头像

                //首次登录  未进行过注册
                member = new UcenterMember();
                member.setAvatar(headimgurl);
                member.setNickname(nickname);
                member.setOpenid(openid);
                ucenterMemberService.save(member);
            }
            //可以通过使用cookie将扫码人信息传到前端 但是cookie不能跨域 所以实际项目中不推荐
            //这里使用token将扫码人信息传递到前端
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;

        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001,"登录失败");
        }

    }
    //生成微信二维码
    @GetMapping("login")
    public String getWxCode(){
        //可以使用固定地址在后面拼接参数  但是不推荐

        // 微信开放平台授权baseUrl 按照微信要求的参数拼接
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_uri进行encode编码
        String encodeUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            encodeUrl =   URLEncoder.encode(encodeUrl,"utf-8");//url编码
        } catch (UnsupportedEncodingException e) {
            throw new GuliException(20001, e.getMessage());
        }
        String url = String.format(baseUrl, ConstantWxUtils.WX_OPEN_APP_ID, encodeUrl, "guli");
        return "redirect:"+url;
    }
}
